package com.arron.algorithm.leetcodetop100.二分查找;

/**
 *  34. 在排序数组中查找元素的第一个和最后一个位置
 */
public class 排序数组中查找元素的第一个和最后一个位置 {



    public int[] searchRange(int[] nums, int target) {
            return new int[]{searchLeftedge(nums,target),searchRightedge(nums,target)};
    }


    /**
     * 寻找有序数组中target出现的左边界
     */
    public int searchLeftedge(int[] nums, int target){

        int left =0,right = nums.length-1;

        while (left<=right){

            int mid = left + (right-left)/2;

            if (nums[mid] == target){
                right = mid-1;
            }else if (nums[mid] <target){
                left = mid+1;
            }else if (nums[mid] > target){
                right = mid-1;
            }



        }

        if (left > nums.length-1 || nums[left] != target){
            return -1;
        }

        return left;
    }


    public int searchRightedge(int[] nums, int target){

        int left =0,right = nums.length-1;

        while (left<=right){

            int mid = left + (right-left)/2;

            if (nums[mid] == target){
                left = mid+1;
            }else if (nums[mid] < target){
                left = mid+1;
            }else if (nums[mid] > target){
                right = mid-1;
            }

        }

        if (right < 0 || nums[right] != target){
            return -1;
        }

        return right;
    }



}
